package com.example.validate;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;
import java.net.UnknownHostException;
import java.text.DateFormat;
import java.util.Date;
import java.util.Locale;


public class RecoveryMail {
	//fields
	private Socket smtp_socket = null;
	private DataOutputStream os = null;
	private DataInputStream is = null;
	private Date d_date;
	private DateFormat d_format;
	//TODO: Make these static
	private String server_hostname;
	private int server_port; 
	
	//constructor
	public RecoveryMail(){
		//empty
		d_date = new Date();
		d_format = DateFormat.getDateInstance(DateFormat.FULL, Locale.getDefault());
		server_hostname = "smtp.stud.ntnu.no";
		server_port = 25;
	}
	
	//methods
	public void connect(){
		try {
			smtp_socket = new Socket(server_hostname, server_port);
			os = new DataOutputStream(smtp_socket.getOutputStream());
			is = new DataInputStream(smtp_socket.getInputStream());
			
			//TODO: Write to log
		} catch (UnknownHostException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}
	
	public int sendMail(String recipient, String subject, String body){
		try {
			os.writeBytes("HELO "+server_hostname+" \r\n");
			//send from
			os.writeBytes("MAIL From: noreply@hackme.com\r\n");
			//send to
			os.writeBytes("RCPT To: "+recipient+"\r\n");
			
			//add the message and the header
			os.writeBytes("DATA\r\n");
			//os.writeBytes("Recovery system\r\n");
		    os.writeBytes("DATE: " + d_format.format(d_date) + "\r\n");
		    os.writeBytes("From: LUT2 <noreply@hackme.com>\r\n");
		    os.writeBytes("To:  YOU <"+recipient+">\r\n");
		    
		    
		    os.writeBytes("Subject: "+subject+"\r\n");
		    os.writeBytes(body + "\r\n");
		    os.writeBytes("\r\n.\r\n");
		    os.writeBytes("QUIT\r\n");
		                
		    // Now send the email off and check the server reply.  
		    // Was an OK is reached you are complete.
		    String responseline;
		    while((responseline = is.readLine())!=null)
		    {  // System.out.println(responseline);
		        if(responseline.indexOf("Ok") != -1)
		            break;
		    }
		    
			
		}catch(Exception e){
			e.printStackTrace();
		}
		
		
		
		
		return 0;
		
	}
	
}
